package com.baizhi.service;

import com.baizhi.dao.UserMapper;
import com.baizhi.entity.User;
import com.baizhi.entity.UserExample;
import com.baizhi.util.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService{

    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        UserExample userExample = new UserExample();
        return userMapper.selectByExample(userExample);
    }

    @Override
    public User login(String username, String password) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        if(users.size()!=0){
            for (User user : users) {
                if(user.getStatus()==0){
                    if(/*MD5Util.getMD5((user.getSalt()+password)).equals(user.getPassword())*/user.getPassword().equals(password)){
                        return user;
                    }
                    throw new RuntimeException("密码错误");
                }
                throw new RuntimeException("不好意思，你的账号被封了");
            }
        }
        throw new RuntimeException("用户名错误");
    }

    @Override
    public User findById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(User user) {

        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void save(User user) {
        user.setId(UUID.randomUUID().toString());
        user.setStatus(0);
        String salt = MD5Util.getSalt(4);
        user.setSalt(salt);
        user.setPassword(MD5Util.getMD5((salt+user.getPassword())));
        userMapper.insert(user);
    }
}
